package com.jrx.anytxn.param.job.bactchBillCompare.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.config.BillCompareConfig;
import com.jrx.anytxn.param.config.PathFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.IOException;

/**
 * 核心对账-账务文件检查是否存在job
 *
 * @author : zcc
 * 2020/11/26
 */
@Configuration
@EnableConfigurationProperties(PathFileConfig.class)
public class BatchBillFileCheckConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(BatchBillFileCheckConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private IOrganizationTableService organizationTableService;

    @Autowired
    private BillCompareConfig billCompareConfig;


    @Bean
    public Job billFileCheckJob() throws IOException {
        return jobBuilderFactory.get("billFileCheckJob")
                .start(billFileCheckStep())
                .build();
    }

    @Bean
    public Step billFileCheckStep() throws IOException {
        return stepBuilderFactory.get("billFileCheckStep").tasklet(billFileCheckTasklet()).build();
    }

    @Bean
    public Tasklet billFileCheckTasklet() {
        return (stepContribution, chunkContext) -> {
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            String fileDate = DateUtils.format(org.getToday(),"yyyyMMdd");
            String businessDate = DateUtils.format(org.getToday());

            String billFileForFK = null;  //放款对账文件
            String billFileForHK = null;  //还款对账文件

            if(Constant.YES_FLAG.equals(billCompareConfig.getCompareFK())){
                billFileForFK = billCompareConfig.getFilePath() + File.separator + fileDate + File.separator + org.getTenantId() + File.separator + billCompareConfig.getPayBankId()+ "_"
                        + billCompareConfig.getPayBusinessId() + "_1_T_" + fileDate + ".txt";
                logger.info("放款对账文件路径为:{},业务日期为:{}", billFileForFK, businessDate);
            }

            if(Constant.YES_FLAG.equals(billCompareConfig.getCompareHK())){
                billFileForHK = billCompareConfig.getFilePath() + File.separator + fileDate + File.separator + org.getTenantId() + File.separator + billCompareConfig.getPayBankId()+ "_"
                        + billCompareConfig.getPayBusinessId() + "_13_T_" + fileDate + ".txt";
                logger.info("还款对账文件路径为:{},业务日期为:{}", billFileForHK, businessDate);
            }


            int i = 1;

            // 循环检查一定次数，超出次数后抛出异常
            while (i <= billCompareConfig.getReadCount()) {

                int checkStatus = 1;      //文件是否存在：0-不存在，1-存在
                String notExistFile = ""; //不存在的账务文件名

                if(Constant.YES_FLAG.equals(billCompareConfig.getCompareFK())){
                    File dirFile = new File(billFileForFK);
                    if (!dirFile.exists()) {
                        checkStatus = 0;
                        notExistFile = billFileForFK;
                    }
                }

                if(Constant.YES_FLAG.equals(billCompareConfig.getCompareHK())) {
                    File dirFile = new File(billFileForHK);
                    if (!dirFile.exists()) {
                        checkStatus = 0;
                        notExistFile = billFileForHK;
                    }
                }

                // 检查不通过，重复进行检查
                if (0 == checkStatus) {
                    logger.error("账务文件【{}】不存在,业务日期为:{}", notExistFile, businessDate);
                    Thread.sleep(billCompareConfig.getReadPeriod());
                    i++;
                } else {
                    logger.info("账务文件检查通过,业务日期为:{}", businessDate);
                    return RepeatStatus.FINISHED;
                }
            }
            // 循环检查超出次数，抛出异常
            if(i > billCompareConfig.getReadCount()){
                logger.error("账务文件循环检查已超过{}次，检查作业将停止。业务日期为:{}", billCompareConfig.getReadCount(), businessDate);
                throw new Exception("账务文件循环检查已超最大次数，检查作业将停止。");
            }
            return RepeatStatus.FINISHED;
        };
    }
}